import Watcher from "./observe/watcher"
import { createElementNode, createTextNode } from "./vdom"
import { patch } from "./vdom/patch"

export function initLifeCycle(Vue) {
  Vue.prototype._c = function () {
    return createElementNode(this, ...arguments)
  }
  Vue.prototype._v = function () {
    return createTextNode(this, ...arguments)
  }
  Vue.prototype._s = function (value) {
    return typeof value === "object" ? JSON.stringify(value) : value
  }
  // 调用生成的render函数
  Vue.prototype._render = function () {
    return this.$options.render.call(this)
  }
  Vue.prototype._update = function (vnode) {
    let vm = this
    let el = vm.$el

    let prevVnode = vm._vnode
    vm._vnode = vnode
    if (prevVnode) {
      // 如果有，说明不是初始渲染
      vm.$el = patch(prevVnode, vnode)
    } else {
      // 初始渲染
      vm.$el = patch(el, vnode)
    }
  }
}

/**
 * _render 预渲染生成虚拟dom
 * _update 生成真实dom，并挂载
 */
export function mountComponent(vm, el) {
  vm.$el = el
  const updateComponent = () => {
    vm._update(vm._render())
  }

  // 初始渲染生成watcher
  let watcher = new Watcher(vm, updateComponent, true)
  // console.log(watcher)
}

export function callHook(vm, hookName) {
  let handlers = vm.$options[hookName]
  if (handlers) {
    handlers.forEach(hook => hook.call(vm))
  }
}
